package com.happy.mycar;

import android.Manifest;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.happy.mycar.databinding.ActivityMainBinding;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private static final int REQ_PERMISSION_CODE = 1;

    private ActivityMainBinding binding;

    public ArrayList<String> requestList = new ArrayList<>();
    private void getPermision() {
        requestList.clear(); // 清空之前的请求列表

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            requestList.add(Manifest.permission.BLUETOOTH);
            requestList.add(Manifest.permission.BLUETOOTH_SCAN);
            requestList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
            requestList.add(Manifest.permission.BLUETOOTH_CONNECT);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            requestList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            requestList.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            requestList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requestList.add(Manifest.permission.POST_NOTIFICATIONS);
            requestList.add(Manifest.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            requestList.add(Manifest.permission.FOREGROUND_SERVICE);
        }

        // 检查是否有需要请求的权限
        if (!requestList.isEmpty()) {
            ActivityCompat.requestPermissions(this, requestList.toArray(new String[0]), REQ_PERMISSION_CODE);
        }
    }
    private boolean isServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        if (manager != null) {
            for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                if (serviceClass.getName().equals(service.service.getClassName())) {
                    return true;
                }
            }
        }
        return false;
    }
    private void showBatteryOptimizationDialog() {
        new AlertDialog.Builder(this)
                .setTitle("后台运行权限")
                .setMessage("请允许本应用忽略电池优化，以确保后台功能正常")
                .setPositiveButton("去设置", (dialog, which) -> PowerUtils.requestIgnoreBatteryOptimization(MainActivity.this))
                .setNegativeButton("取消", null)
                .show();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //StatusBar statusBar = new StatusBar(this);
        //statusBar.setColor(R.color.white);
        //statusBar.setStatusBarTextDark(getWindow(),false);
        EdgeToEdge.enable(this);

        super.onCreate(savedInstanceState);
        getPermision();
        boolean notificationPermissionGranted = NotificationManagerCompat.from(this).areNotificationsEnabled();
        if (!notificationPermissionGranted) {
            // 请求通知权限
            Intent intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
                    .putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
            startActivity(intent);
        }
        MyBLEService.createNotificationChannel(getApplication());
        CBLEDevice.getInstance().setContext(getApplicationContext());
        // 使用 WorkManager 调度任务
        //MyBLEWorker.doWorke(getApplication());
        //判断前台服务是否已经启动
        if (!isServiceRunning(MyBLEService.class)) {
            // 启动前台服务
            Intent serviceIntent = new Intent(getApplication(), MyBLEService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(serviceIntent);
            } else {
                startService(serviceIntent);
            }
        }
        if (!PowerUtils.isIgnoringBatteryOptimizations(this)) {
            showBatteryOptimizationDialog();
        }

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_mycar, R.id.navigation_set, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
        //NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(binding.navView, navController);
    }

}